import axios from "axios";
import config from "../config";

export const RequestFactory = ({ conf }) => {
  const request = axios.create({
    baseURL: config.proxyUrl,
    headers: {
      'Content-Type': 'application/json',
    },
  })

  return {
    request: async (options) => {
      if (!options.params) options.params = {};

      const params = {
        org_id: conf.get('org_id'),
        user_token: conf.get('ai_user_token'),
        cur_env: "desktop",
        team_id: conf.get('ai_user_team'),
      };

      if (options.data) {
        if(options.data instanceof FormData){
          for (let key in params) {
            options.data.append(key, params[key])
          }
        } else {
          options.data = {
            ...options.data,
            ...params
          }
        }
      } else {
        options.params = {
          ...options.params,
          ...params
        }
      }

      const response = await request(options)

      const { code, msg: message } = response.data || {};

      if (! response.data){
        throw new Error('哎呀，网络请求超时，请稍后再试')
      } else if (code !== 1000) {
        throw new Error(message || '系统未知错误，请反馈给管理员')
      }

      return response.data
    }
  }
}